//
//  MainAppController.m
//  iSwitchView
//
//  Created by Ronnie on 08-12-3.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "MainAppController.h"
#import "DialogWindowController.h"
#import "MainWindowController.h"


@implementation MainAppController

- (void) dealloc
{
	[myFetionData release];
	[mainWindowController release];
	[super dealloc];
}


- (void)setMainWindowController:(MainWindowController*)mainWindowCtrl
{
	mainWindowController = [mainWindowCtrl retain];
}
- (MainWindowController*)getMainWindowController
{
	return mainWindowController;
}

- (void)fxLogin:(NSString*)user password:(NSString*)passwd status:(int)loginState
{
	if (!fx_init())
	{
		fprintf(stderr, "init the app fail \n");
		return;	
	}
	
	fx_set_login_status(loginState);
	if ( !fx_login([user UTF8String], [passwd UTF8String], (My_EventListener), self) )
	{
		return;
	}
	printf("Login is invoked\n");
}

- (void)fxCancelLogin
{
	//fx_loginout ();
	//fx_close_network();
	fx_terminate();
	fx_close_network();
}

#pragma mark send notification
- (void)addNotificationResponser
{
}
- (void)notifyMainWindowToResize
{
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
	//NSLog(@"Sending notification of login");
	[nc postNotificationName:@"FETION_HAVE_LOGIN" object:nil];
}


- (void)notifyGetSomeBuddyMessage:(long)uid
{
	char message[2048];
	
	FXTreeNode* node = [myFetionData getFXTreeNodeById:uid];
	Fetion_MSG *msg = fx_get_msg(uid);
	sprintf(message,"<Message>%s</Message>", msg->message);
	
	NSError *err=nil;
	NSXMLElement* xmlElem = [[NSXMLElement alloc] initWithXMLString:[NSString stringWithUTF8String:message] error:&err];
	NSMutableString* tempMSM = [[NSMutableString stringWithUTF8String:""] retain];
	for (int i=0; i<[[xmlElem children] count]; i++) {
		[tempMSM appendString:[[[xmlElem children] objectAtIndex:i] objectValue]];
		if (i!=[[xmlElem children] count]-1) {
			[tempMSM appendString:[NSString stringWithUTF8String:"\n"]];
		}
	}
	NSLog(@"tempMSM = %@", tempMSM);
	if ( node!=nil && [node isLeaf] ) {
		if (![node getDialogWindowContorller]) {
			[node setDialogWindowController:[[DialogWindowController alloc] init]];
			[[node getDialogWindowContorller] showWindow:self];
			[[node getDialogWindowContorller] setChatFriendData:node];
		}
		else
			[[node getDialogWindowContorller] showWindow:self];

		//[[node getDialogWindowContorller] getAMSM:tempMSM];
		[[node getDialogWindowContorller] performSelectorOnMainThread:@selector(getAMSM:) withObject:tempMSM waitUntilDone:nil];
	}
	
	[tempMSM release];
	
	fx_destroy_msg(msg);
}

- (void)notifySomeBuddyChangeStatus:(long)uid
{
	FXSysMessage* sysMessage = [[FXSysMessage alloc] initWithLParam:uid WParam:-1];
	[[mainWindowController getListController] performSelectorOnMainThread:@selector(changStageById:) withObject:sysMessage waitUntilDone:nil];
	[sysMessage autorelease];
}

- (void)notifyMoveGroupOKById:(long)uid ToGroup:(int)groupId
{
	FXSysMessage* sysMessage = [[FXSysMessage alloc] initWithLParam:uid WParam:groupId];
	[[mainWindowController getListController] performSelectorOnMainThread:@selector(moveGroupOKWith:) withObject:sysMessage waitUntilDone:NO];
	[sysMessage autorelease];
}

- (void)notifyChangeStatusOK:(int)status
{
	FXSysMessage* sysMessage = [[FXSysMessage alloc] initWithLParam:-1 WParam:status];
	[[[[mainWindowController window] toolbar] delegate] performSelectorOnMainThread:@selector(updateViewByStatus:) withObject:sysMessage waitUntilDone:NO];
	[sysMessage autorelease];
}

- (void)notifyChangeUserLocalName:(long)uid
{
	FXSysMessage* sysMessage = [[FXSysMessage alloc] initWithLParam:uid WParam:-1];
	[[mainWindowController getListController] performSelectorOnMainThread:@selector(changeUserLocalName:) withObject:sysMessage waitUntilDone:NO];
	[sysMessage autorelease];
}

- (void)notifyRenameGroup:(int)groupId
{
	FXSysMessage* sysMessage = [[FXSysMessage alloc] initWithLParam:-1 WParam:groupId];
	[[mainWindowController getListController] performSelectorOnMainThread:@selector(changeGroupName:) withObject:sysMessage waitUntilDone:NO];
	[sysMessage autorelease];
}

- (void)notifyDeleteBuddy:(long)uid
{
	FXSysMessage* sysMessage = [[FXSysMessage alloc] initWithLParam:uid WParam:-1];
	[[mainWindowController getListController] performSelectorOnMainThread:@selector(deleteBuddy:) withObject:sysMessage waitUntilDone:NO];
	[sysMessage autorelease];
}

- (void)notifyDeleteGroup:(int)groupId
{
	FXSysMessage* sysMessage = [[FXSysMessage alloc] initWithLParam:-1 WParam:groupId];
	[[mainWindowController getListController] performSelectorOnMainThread:@selector(deleteGroup:) withObject:sysMessage waitUntilDone:NO];
	[sysMessage autorelease];
}

- (void)notifyAddGroup:(int)groupId
{
	FXSysMessage* sysMessage = [[FXSysMessage alloc] initWithLParam:-1 WParam:groupId];
	[[mainWindowController getListController] performSelectorOnMainThread:@selector(addGroup:) withObject:sysMessage waitUntilDone:NO];
	[sysMessage autorelease];
}

- (void)notifyAddBuddy:(long)uid toGroup:(int)gid
{
	FXSysMessage* sysMessage = [[FXSysMessage alloc] initWithLParam:uid WParam:gid];
	[[mainWindowController getListController] performSelectorOnMainThread:@selector(addBuddy:) withObject:sysMessage waitUntilDone:NO];
	[sysMessage autorelease];
}

- (void)requestFXDataFromNet
{	
	myFetionData = [[FXDataCenter alloc] initFromNet];
	[myFetionData PrintBuddyList];
	fx_set_system_msg_cb (Sys_EventListener, self);
}


- (FXDataCenter*)getFxData
{
	return myFetionData;
}

@end


void My_EventListener(int message, WPARAM wParam, LPARAM lParam, void* args)
{	
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	MainAppController* mainAppCtrl = (MainAppController*)args;
	switch(message)
	{
		case FX_LOGIN_URI_ERROR:
			printf("FX_LOGIN_URI_ERROR  手机号或fetion号错误 \n");
			[[[mainAppCtrl getMainWindowController] getLoginController] setMyHint:@"手机号或fetion号错误"];
			break;
			
		case FX_LOGIN_CONNECTING:
			printf("FX_LOGIN_CONNECTING   正在连接服务器 \n");
			[[[mainAppCtrl getMainWindowController] getLoginController] setMyHint:@"正在连接服务器"];
			break;
			
		case FX_LOGIN_WAIT_AUTH:
			printf("FX_LOGIN_WAIT_AUTH  正在验证用户名和密码\n");
			[[[mainAppCtrl getMainWindowController] getLoginController] setMyHint:@"正在验证用户名和密码"];
			break;
			
		case FX_LOGIN_AUTH_OK:
			printf("FX_LOGIN_WAIT_AUTH 验证用户名和密码成功\n");
			[[[mainAppCtrl getMainWindowController] getLoginController] setMyHint:@"验证用户名和密码成功"];
			break;
			
		case FX_LOGIN_FAIL:
			printf("FX_LOGIN_FAIL 登陆失败\n");
			[[[mainAppCtrl getMainWindowController] getLoginController] setMyHint:@"登陆失败"];
			break;
		case FX_LOGIN_NETWORK_ERROR:
			printf("FX_LOGIN_NETWORK_ERROR 网络错误\n");
			[[[mainAppCtrl getMainWindowController] getLoginController] setMyHint:@"网络错误"];
			break;
		case FX_LOGIN_UNKOWN_ERROR :   
			printf("FX_LOGIN_UNKOWN_ERROR 登陆出现未知错误\n");
			[[[mainAppCtrl getMainWindowController] getLoginController] setMyHint:@"登陆出现未知错误"];
			break;
			
		case FX_LOGIN_UNKOWN_USR:
			printf("FX_LOGIN_UNKOWN_USR 用户名错误\n");
			[[[mainAppCtrl getMainWindowController] getLoginController] setMyHint:@"用户名错误"];
			break;
			
		case FX_LOGIN_GCL_GETTING:
			printf("FX_LOGIN_GCL_GETTING 正在获取联系人列表\n");
			[[[mainAppCtrl getMainWindowController] getLoginController] setMyHint:@"正在获取联系人列表"];
			break;
			
		case FX_LOGIN_GCL_OK:   
			printf("FX_LOGIN_GCL_OK 获取联系人列表成功\n");
			[[[mainAppCtrl getMainWindowController] getLoginController] setMyHint:@"获取联系人列表成功"];
			break;
			
		case FX_LOGIN_GCL_FAIL:
			printf("FX_LOGIN_GCL_FAIL 获取联系人列表失败\n");
			[[[mainAppCtrl getMainWindowController] getLoginController] setMyHint:@"获取联系人列表失败"];
			break;
			
		case FX_LOGIN_GP_GETTING:
			printf("FX_LOGIN_GP_GETTING 正在获取联系人信息\n");
			[[[mainAppCtrl getMainWindowController] getLoginController] setMyHint:@"正在获取联系人信息"];
			break;
			
		case FX_LOGIN_GP_OK:
			printf("FX_LOGIN_GP_OK 获取联系人信息成功\n");
			[[[mainAppCtrl getMainWindowController] getLoginController] setMyHint:@"获取联系人信息成功"];
			break;
		case FX_LOGIN_GP_FAIL:
			printf("FX_LOGIN_GP_FAIL 获取联系人信息失败\n");
			[[[mainAppCtrl getMainWindowController] getLoginController] setMyHint:@"获取联系人信息失败"];
			break;
			
		case FX_LOGIN_OK :
			printf("FX_LOGIN_OK 登陆成功\n");
			[[[mainAppCtrl getMainWindowController] getLoginController] setMyHint:@"登陆成功"];
			[mainAppCtrl requestFXDataFromNet];
			[mainAppCtrl notifyMainWindowToResize];
			break;
	}
	[pool drain];
}

void Sys_EventListener(int message, WPARAM wParam, LPARAM lParam, void* args)
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	MainAppController* mainAppCtrl = (MainAppController*)args;
	switch(message)
	{
		case FX_CURRENT_VERSION:
			break;
		case FX_ADDACCOUNT_APP:
			break;
		case FX_MOVE_GROUP_OK:
			printf("Move the group %ld %i!\n", (long)lParam, (int)wParam);
			[mainAppCtrl notifyMoveGroupOKById:(long)lParam ToGroup:(int)wParam];
			break;
		case FX_MOVE_GROUP_FAIL:
			break;
		case FX_SYS_MESSAGE:
			break;
		case FX_NEW_MESSAGE:
			printf("Get a new message from %ld!\n", (long)lParam);
			[mainAppCtrl notifyGetSomeBuddyMessage:(long)lParam];
			break;
		case FX_NEW_QUN_MESSAGE:
			break;
		case FX_SET_STATE_OK:
			printf("Set %ld's state is changed to %i!\n", (long)lParam, (int)wParam);
			[mainAppCtrl notifyChangeStatusOK:(int)wParam];
			break;
		case FX_STATUS_OFFLINE:
		case FX_STATUS_ONLINE:
		case FX_STATUS_BUSY:
		case FX_STATUS_AWAY:
		case FX_STATUS_MEETING:
		case FX_STATUS_PHONE:
		case FX_STATUS_DINNER:
		case FX_STATUS_EXTENDED_AWAY: 
		case FX_STATUS_NUM_PRIMITIVES:
		case FX_ACCOUNT_UPDATA_OK:
			// add method to process this event,like change state;
			// here is a problem, if I update the account, it will resend many thus messages.
			printf("Receive event that %i change state\n", (long)lParam);
			[mainAppCtrl notifySomeBuddyChangeStatus:(long)lParam];
			break;
			
		case FX_STATUS_SMSEXTENED:
			//printf("have receive the FX_STATUS_SMSEXTENED message of %d %ld\n", wParam, lParam);
			//emit signal_UpdateAcInfo(qlonglong(lParam));
			break;
		case FX_SET_REFUSE_SMS_DAY_OK:
			break;
		case FX_REMOVE_BLACKLIST_OK:
		case FX_ADD_BLACKLIST_OK:
			printf("Buddy %i add or remove from blacklist\n", (long)lParam);
			[mainAppCtrl notifySomeBuddyChangeStatus:(long)lParam];
			break;
		case FX_SYS_ERR_NETWORK:
			break;
		case FX_SYS_DEREGISTERED:
			break;
		case FX_DIA_SEND_OK: 
		case FX_DIA_SEND_FAIL: 
		case FX_DIA_SEND_TIMEOUT: 
		case FX_SMS_OK: 
		case FX_SMS_FAIL: 
		case FX_SMS_FAIL_LIMIT: 
		case FX_SMS_TIMEOUT: 
		case FX_QUN_SEND_OK: 
		case FX_QUN_SEND_FAIL: 
		case FX_QUN_SEND_TIMEOUT: 
		case FX_QUN_SMS_OK: 
		case FX_QUN_SMS_FAIL: 
		case FX_QUN_SMS_FAIL_LIMIT:
		case FX_QUN_SMS_TIMEOUT:
			break;
		case FX_ADD_BUDDY_OK:
			printf("Add buddy %ld to group %dn", (long)lParam, (int)wParam);
			[mainAppCtrl notifyAddBuddy:(long)lParam toGroup:(int)wParam];
			break;
		case FX_RENAME_GROUP_OK:
			printf("Rename group: %ld %i!\n", (long)lParam, (int)wParam);
			[mainAppCtrl notifyRenameGroup:(long)lParam];
			break;
		case FX_SET_BUDDY_INFO_OK:
			printf("Set buddy info: %ld %d!\n", (long)lParam, (int)wParam);
			[mainAppCtrl notifyChangeUserLocalName:(long)lParam];
			break;
		case FX_ADD_GROUP_OK:
			printf("add group %id %i is ok\n", (long)lParam, (int)wParam);
			[mainAppCtrl notifyAddGroup:(long)lParam];
			break;
		case FX_DEL_GROUP_OK:
			printf("Delete group %ld %i successes\n", (long)lParam, (int)wParam);
			[mainAppCtrl notifyDeleteGroup:(long)lParam];
			break;
		case FX_DEL_BUDDY_OK:
			printf("Delete buddy %ld successes\n", (long)lParam);
			[mainAppCtrl notifyDeleteBuddy:(long)lParam];
			break;
		case FX_ADD_GROUP_FAIL:
		case FX_DEL_GROUP_FAIL:
		case FX_SET_BUDDY_INFO_FAIL:
		case FX_RENAME_GROUP_FAIL:
			break;
		case FX_SET_NICKNAME_OK:
			break;
		default:
			break;
	}
	[pool drain];
}